<template>
  <Modal
    v-bind="$attrs"
    :closable="closable"
    :keyboard="keyboard"
    :maskClosable="maskClosable"
    :footer="footer"
    width="80%"
    :bodyStyle="{ height: 'fit-content', maxHeight: '100vh' }"
  >
    <div class="relative h-[78vh] w-full overflow-hidden">
      <img class="absolute left-0 top-0 h-full w-full" :src="src" />
      <div class="modal_container" @dragover="dragover" @click="onAdd">
        <div
          v-for="item in pointList"
          :style="currentStyle(item)"
          class="device_icon"
          @dragend="(e) => appendDom(e, item.type, item)"
          :draggable="isConfig ? false : true"
        ></div>
        <div class="config" :style="configStyle" @click.stop>
          <div class="left" v-if="!isClose">
            <CaretLeftOutlined @click="onMove(true)" />
          </div>
          <div class="right" v-else>
            <CaretRightOutlined @click="onMove(false)" />
          </div>
          <div v-if="!isClose" class="content">
            <div :style="toolStyle" class="tool">
              <div class="modal_title">
                <span>二维信息</span>
                <Button @click="isConfig = false">配置</Button>
              </div>
              <div class="modal_content">
                <div class="label">名称:</div>
                <div>{{ structureName }}</div>
                <div class="label">关联设备:</div>
                <div class="device" v-for="item in deviceList">
                  <img :src="`/static/${item.type}.png`" alt="" />
                  <span>{{ item.label }}</span>
                  <span>{{ item.value }}</span>
                </div>
                <!-- <div class="label">当前告警设备:</div>
              <div class="device" v-for="item in alarmList">
                <img
                  :src="`/static/${item.type}.png`"
                  alt=""
                  :draggable="false"
                />
                <span>{{ deviceEnum[item.type] }}</span>
                <span>{{ item.status }}</span>
              </div> -->
              </div>
            </div>
            <div :style="infoStyle" class="info">
              <div class="modal_title">
                <span>目录</span>
                <Button @click="isConfig = true">返回</Button>
              </div>
              <div class="modal_content">
                <div class="label">测点列表:</div>
                <Tree
                  :tree-data="treeInfo"
                  defaultExpandAll
                  v-model:selectedKeys="selectedKeys"
                >
                  <template #title="{ type, title }">
                    <span
                      v-if="type == '4'"
                      :draggable="true"
                      @dragstart="_dragstart"
                      @dragend="_dragend"
                      >{{ title }}</span
                    >
                    <span v-else>{{ title }}</span>
                  </template>
                </Tree>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-for="(slotContent, slotName) in slots" :key="slotName">
        <slot :name="slotName"></slot>
      </div>
    </div>
  </Modal>
  <FormModal :columns="_item" :model="deviceInfo">
    <template #label1> <span class="form_label">描点信息</span> </template>
    <template #label2> <span class="form_label">设备信息</span> </template>
    <template #deviceType>
      <FormItemRest>
        <BoTable
          :columns="columns"
          :request="_request"
          :row-selection="rowSelection"
          hideSearch
          row-key="deviceType"
          height="auto"
        ></BoTable>
      </FormItemRest>
    </template>
  </FormModal>
</template>

<script setup lang="tsx">
import { PropType, computed, onMounted, ref, useSlots } from 'vue';
import { CaretLeftOutlined, CaretRightOutlined } from '@ant-design/icons-vue';
import { useFormModal } from '@boeyo/hooks';
import {
  BoFormProps,
  BoTable,
  BoTableProps,
  valueEnumToOptions,
} from '@boeyo/ui';
import { Button, FormItemRest, Modal, Tree, message } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';

const props = defineProps({
  closable: {
    type: Boolean,
    default: false,
  },
  keyboard: {
    type: Boolean,
    default: false,
  },
  maskClosable: {
    type: Boolean,
    default: false,
  },
  footer: {
    type: Boolean,
    default: false,
  },
  src: {
    type: String,
    default: '/api/profile/upload/2025/03/19/icon%20(1)_20250319145655A001.png',
  },
  structureName: {
    type: String,
    required: true,
  },
  deviceEnum: {
    type: Object,
    default: {
      earthquake: '强震仪',
      terminal: '边缘终端',
      power: '智能电源',
    },
  },
  deviceList: {
    type: Array as PropType<Array<{ label: string; value: string }>>,
    default: [],
  },
  treeData: {
    type: Array,
    default: [],
  },
  list: {
    type: Array,
    default: [],
  },
});

const emit = defineEmits(['update:list']);
const treeInfo = cloneDeep(props.treeData);
const { FormModal, open } = useFormModal({
  size: 'middle',
  column: 1,
});

const deviceInfo = ref({});
const _item = computed<BoFormProps['columns']>(() => [
  {
    title: '',
    dataIndex: 'label1',
    valueType: 'input',
    formItemProps: {
      wrapperCol: { span: 24 },
    },
  },
  {
    title: '测点名称',
    dataIndex: 'name',
    valueType: 'select',
    formItemProps: {
      wrapperCol: { span: 6 },
      labelCol: { style: { width: '120px' } },
      rules: [
        {
          required: true,
          message: '请选择测点!',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请选择测点',
      options: [
        { label: '测点1', value: 1 },
        { label: '测点2', value: 2 },
      ],
    },
  },
  {
    title: '',
    dataIndex: 'label2',
    valueType: 'input',
    formItemProps: {
      wrapperCol: { span: 24 },
    },
  },
  {
    title: '',
    dataIndex: 'deviceType',
    valueType: 'radio',
    formItemProps: {
      wrapperCol: { span: 24 },
      rules: [
        {
          required: true,
          message: '请选择设备类型!',
          trigger: 'blur',
        },
      ],
    },
  },
]);
const selectedKeys = ref(['3']);
const slots = useSlots();
const isClose = ref(false);
const isConfig = ref(true);
const configStyle = computed(() => {
  return {
    width: isClose.value ? 0 : '15vw',
  };
});

const toolStyle = computed(() => {
  return {
    width: isConfig.value ? '100%' : 0,
  };
});
const infoStyle = computed(() => {
  return {
    width: !isConfig.value ? '100%' : 0,
  };
});
const onMove = (val) => {
  isClose.value = val;
};

// const alarmList = [
//   {
//     label: 'ios005强震仪',
//     status: '告警中',
//     type: 'earthquake',
//   },
//   {
//     label: 'ios005强震仪',
//     status: '告警中',
//     type: 'earthquake',
//   },
//   {
//     label: 'ios005强震仪',
//     status: '告警中',
//     type: 'earthquake',
//   },
// ];
const pointList = ref([]);
const appendDom = (e, type, currentItem?) => {
  if (isConfig.value) return;
  const dom = document.querySelector('.modal_container');
  const rect = dom.getBoundingClientRect();
  const distanceFromTop = rect.top + window.scrollY;
  const distanceFromLeft = rect.left + window.scrollX;
  //计算盒子距离图片盒子精确距离
  const currentLeft = e.clientX - distanceFromLeft - window.innerWidth * 0.01;
  const currentTop = e.clientY - distanceFromTop - window.innerWidth * 0.01;
  if (
    currentLeft < 0 ||
    currentTop < 0 ||
    currentLeft > rect.width ||
    currentTop > rect.height
  )
    return message.info('超出可添加设备范围!');
  const left = ((currentLeft / rect.width) * 100).toFixed(4) + '%';
  const top = ((currentTop / rect.height) * 100).toFixed(4) + '%';

  if (currentItem) {
    currentItem.top = top;
    currentItem.left = left;
  } else {
    pointList.value.push({
      top,
      left,
      type,
    });
  }
  emit('update:list', pointList.value);
};
const dragover = (e) => {
  e.preventDefault();
};

const currentStyle = (item) => {
  return {
    top: item.top,
    left: item.left,
    background: `url(/static/${item.type}.png)`,
    backgroundSize: 'cover',
    backgroundPosition: 'center',
  };
};

const _dragstart = () => {
  setTimeout(() => {
    isClose.value = true;
  }, 0);
};
const _dragend = (e) => {
  isClose.value = false;
  deviceInfo.value = {};
  // open({
  //   title: '配置描点',
  //   request: async (params) => {
  //     appendDom(e, params.deviceType);
  //     message.success('操作成功!');
  //   },
  //   defaultValue: {},
  // });
};
const _request = () => {
  return {
    total: 3,
    rows: [
      {
        id: '1',
        deviceName: '强震仪',
        deviceType: 'earthquake',
        deviceCode: '设备型号',
        name: '博远',
        amount: 'A00001',
        version: '1.0',
        longitude: '116.23',
        latitude: '116.23',
        elevation: '112',
      },
      {
        id: '2',
        deviceName: '边缘终端',
        deviceType: 'terminal',
        deviceCode: '设备型号',
        name: '博远',
        amount: 'A00001',
        version: '1.0',
        longitude: '116.23',
        latitude: '116.23',
        elevation: '112',
      },
      {
        id: '3',
        deviceName: '智能电源',
        deviceType: 'power',
        deviceCode: '设备型号',
        name: '博远',
        amount: 'A00001',
        version: '1.0',
        longitude: '116.23',
        latitude: '116.23',
        elevation: '112',
      },
    ],
  };
};

const selectKeys = ref<number[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    type: 'radio',
    onChange(values) {
      selectKeys.value = values as number[];
      deviceInfo.value.deviceType = values[0];
    },
  };
});

const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '设备类型',
    dataIndex: 'deviceName',
  },
  {
    title: '设备型号',
    dataIndex: 'deviceCode',
  },
  {
    title: '设备厂商',
    dataIndex: 'name',
    customRender({ text }) {
      const style = {
        color: '#1677ff',
      };
      return <span style={style}>{text}</span>;
    },
  },
  {
    title: '硬件序列号',
    dataIndex: 'amount',
  },
  {
    title: '软件版本',
    dataIndex: 'version',
  },
  {
    title: '设备经度',
    dataIndex: 'longitude',
  },
  {
    title: '设备纬度',
    dataIndex: 'latitude',
  },
  {
    title: '高程',
    dataIndex: 'elevation',
  },
]);
const onAdd = (e) => {
  deviceInfo.value = {};
  if (isConfig.value) return;
  open({
    modalType: 'add',
    title: '配置描点',
    request: async (params) => {
      appendDom(e, params.deviceType);
      message.success('操作成功!');
    },
    defaultValue: {},
  });
};
</script>

<style lang="scss" scoped>
.modal_container {
  user-select: none;
  display: flex;
  justify-content: space-between;
  padding: 1.5vh;
  position: relative;
  font-size: 1.5vh;
  .config {
    border-radius: 6px;
    margin-right: 1vw;
    background-color: rgba(0, 0, 0, 0.5);
    position: relative;
    transition: width ease 0.3s;
    .left,
    .right {
      cursor: pointer;
      position: absolute;
      right: 5px;
      font-size: 2vh;
      color: #fff;
      top: 50%;
      transform: translateY(-50%);
    }
    .right {
      right: -1vw;
    }
    .content {
      height: calc(100% - 20px);
      margin: 10px;
      display: flex;
      justify-content: space-between;
      overflow: hidden;
    }
    .tool,
    .info {
      transition: width ease 0.3s;
      height: 100%;
      overflow: hidden;
      color: #fff;
      .modal_title {
        display: flex;
        white-space: nowrap;
        justify-content: space-between;
        padding-left: 0.5vw;
        span {
          font-size: 18px;
          font-weight: 700;
        }
      }
      .modal_content {
        padding: 1vw 0 0 0.5vw;
        white-space: nowrap;
        .label {
          padding: 0.5vw 0;
        }
        .device {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 80%;
          padding: 1vw;
          img {
            width: 2vh;
            height: 2vh;
            border-radius: 50%;
          }
          &.draggable {
            &:hover {
              background-color: rgba(0, 0, 0, 0.1);
            }
          }
        }
      }
    }
  }
}
:deep(.ant-tree) {
  background: transparent;
  color: #fff;
  font-size: 1.5vh;
  .ant-tree-switcher-icon {
    font-size: 1.5vh;
  }
  .ant-tree-node-selected {
    background: rgba(255, 255, 255, 0.2);
  }
  .ant-tree-node-content-wrapper {
    line-height: 1.7vh;
  }
}
.form_label {
  font-weight: 700;
}
</style>
<style lang="scss">
.device_icon {
  position: absolute;
  width: 2vw;
  height: 2vw;
  border-radius: 50%;
  cursor: pointer;
}
</style>
